<!--
 * @Author: Rain
 * @Date: 2021-11-24 22:42:40
 * @LastEditTime: 2023/10/22 22:02:43
 * @Description: Do Something
-->
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="flex items-center flex-end">
        <!-- 搜索 -->
        <el-input
          v-model="query.title"
          clearable
          placeholder="标题"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
        <crudOperation :permission="permission" />
      </div>

      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="50%"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" class="w-full" placeholder="输入标题" />
          </el-form-item>
          <el-form-item label="模块" prop="textKey">
            <el-select
              v-model="form.textKey"
              filterable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in dict.richtext_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :default-config="toolbarConfig"
              :mode="mode"
            />
            <!-- 编辑器 -->
            <Editor
              style="height: 300px"
              :default-config="editorConfig"
              :content="defaultContent"
              :mode="mode"
              @onCreated="onCreated"
              @onChange="onChange"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
          >确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="textKey" label="标识">
          <template slot-scope="scope">
            {{ dict.label.richtext_type[scope.row.textKey] }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkPer(['admin', 'richText:edit', 'richText:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudRichText from '@/api/richText'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import cookie from 'js-cookie'
import cloneDeep from 'lodash.clonedeep'

const defaultForm = {
  id: null,
  title: null,
  content: null,
  textKey: null,
  allContent: null
}
export default {
  name: 'RichText',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Editor,
    Toolbar
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['richtext_type'],
  cruds() {
    return CRUD({
      title: '富文本管理',
      url: 'api/richText',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudRichText }
    })
  },
  data() {
    return {
      editor: null,
      permission: {
        add: ['admin', 'richText:add'],
        edit: ['admin', 'richText:edit'],
        del: ['admin', 'richText:del']
      },
      rules: {
        title: [{ required: true, message: '请输入标题' }],
        textKey: [{ required: true, message: '请选择模块' }],
        content: [{ required: true, message: '请输入内容' }]
      },
      queryTypeOptions: [{ key: 'textKey', display_name: '标识' }],
      toolbarConfig: {},
      defaultContent: [
        {
          type: 'paragraph',
          children: [{ text: '' }]
        }
      ],
      editorConfig: {
        placeholder: '请输入内容...',
        readOnly: false,
        MENU_CONF: {
          uploadImage: {
            server: '/api/localStorage/pictures',
            fieldName: 'file',
            withCredentials: true,
            meta: {
              name: new Date().getTime()
            },
            headers: {
              Authorization: cookie.get('EL-ADMIN-TOEKN')
            },
            onBeforeUpload(files) {
              return files
              // 返回值可选择：
              // 1. 返回一个数组（files 或者 files 的一部分），则将上传返回结果中的文件
              // 2. 返回 false ，则终止上传
            },
            // 单个文件上传成功之后
            onSuccess(file, res) {
              console.log(`${file.name} 上传成功`, res)
            },
            // 单个文件上传失败
            onFailed(file, res) {
              console.log(`${file.name} 上传失败`, res)
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
              console.log(`${file.name} 上传出错`, err, res)
            },
            // 自定义插入图片
            customInsert(res, insertFn) {
              const { path } = res
              const url = path.replace('/home/eladmin/', '/')
              insertFn(url)
            }
          }
        }
      },
      mode: 'default', // or 'simple'
      curContent: []
    }
  },
  computed: {
    getDefaultContent() {
      return cloneDeep(this.defaultContent)
    }
  },
  // 及时销毁 editor
  beforeDestroy() {
    if (this.editor == null) return
    this.editor.destroy()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeValidateCU]() {
      if (this.editor == null) return
      if (this.editor.isEmpty()) {
        this.form.allContent = null
        this.form.content = null
      } else {
        this.form.content = this.editor.getHtml()
        this.form.allContent = JSON.stringify(this.editor.children)
      }
    },
    // [CRUD.HOOK.beforeSubmit]() {
    //   const editor = getEditor(this.editorId)
    //   if (editor == null) return
    // },
    [CRUD.HOOK.beforeToCU]() {
      if (this.editor === null) return
      if (this.form.content) {
        this.editor.clear()
        this.editor.setHtml(this.form.content)
        // const content = JSON.parse(this.form.allContent)
        // SlateTransforms.removeNodes(this.editor, { at: [0] })
      } else {
        this.editor.clear()
      }
    },
    onCreated(editor) {
      // 修改 uploadImage 菜单配置
      this.editor = Object.seal(editor)
      editor.setHtml(this.content || '')
      if (this.form.allContent) {
        const content = JSON.parse(this.form.allContent)
        editor.children = content
      }
    },
    onChange(editor) {
      this.curContent = editor.children
    },
    onDestroyed(editor) {
      console.log('onDestroyed', editor)
    },
    onMaxLength(editor) {
      console.log('onMaxLength', editor)
    }
  }
}
</script>

<style scoped></style>
